<template>
  <div>
    <van-nav-bar
      title="人工上报市容顽症事件"
      left-text=""
      left-arrow
            :fixed="true"
      @click-left="onClickLeft"
    />
    <div class="title">事件详情填报</div>
    <van-cell-group>
      <van-cell
        is-link
        title="事件类型"
        @click="typeshow = true"
        :value="typevalue"
      />
      <van-action-sheet
        v-model="typeshow"
        :actions="typeactions"
        @select="typeSelect"
      />
    </van-cell-group>

    <van-cell-group>
      <van-cell
        is-link
        title="发生时间"
        @click="timeshow = true"
        :value="currentDate"
      />
      <!-- <van-calendar
        v-model="timeshow"
        @confirm="timeConfirm"
        :min-date="minDate"
        :default-date="defaultDate"
      /> -->
      <!-- <van-field
        v-model="currentDate"
        placeholder="选择时间" readonly="readonly"
        @click="timeshow = true"
      /> -->
      <van-popup v-model="timeshow" label="离开时间" position="bottom" :overlay="true">
        <van-datetime-picker
          v-model="currentDate_end"
          type="datetime"
          @cancel="endTimePop = false"
          @confirm="endTimePop = false"
          @change="endTimeChange"
          :min-date="minDate"
        />
      </van-popup>
    </van-cell-group>

    <van-cell-group>
      <!-- <van-field
        name="事件地址"
        label="事件地址"
        placeholder="输入工程地址"
        is-link
        title="事件地址"
        @click="addresshandle"
        :value="address"
        :rules="[{ required: true, message: '输入工程地址' }]"
      /> -->
      <van-cell
        is-link
        title="事件地址"
        @click="addresshandle"
        :value="address"
      />

      <van-popup v-model="showArea" position="bottom">
        <div class="map-search">
          <van-search
            v-model="searchMap"
            show-action
            placeholder="请输入搜索关键词"
            @search="onSearch"
            @cancel="onCancel"
          />
        </div>
        <div id="gdmap">
        </div>
      </van-popup>
    </van-cell-group>

    <van-cell-group>
      <van-cell
        is-link
        title="所属网格"
        @click="gridshow = true"
        :value="gridvalue"
      />
      <van-action-sheet
        v-model="gridshow"
        :actions="gridactions"
        @select="gridSelect"
      />
    </van-cell-group>
    <van-cell-group>
      <van-cell title="上传照片" icon="photo-o" />
      <div class="uploadbox">
        <van-uploader
          v-model="uploader"
          :after-read="afterRead"
          :before-delete="picDelete"
          :before-read="beforeRead"
          multiple
          :max-count="6"
        />
      </div>
    </van-cell-group>
    <div class="reportBtn">
      <van-button
        round
        type="info"
        block
        color="linear-gradient(90deg, #00C4C6 0%, #01DC8E 100%)"
        @click="reporthandle"
        >事件上报</van-button
      >
    </div>
    <div class="cancel" @click="cancel">取消</div>
  </div>
</template>

<script>
import { uploadPic , disInsert } from '../../../utils//api'
import  { compressImage } from '../../../config/compressImage'
import { Toast } from 'vant';
export default {
  name: "manualReport",
  data() {
    return {
      typevalue: "",
      typeshow: false,
      typeactions: [{ name: "垃圾溢满" }, { name: "小包垃圾丢弃" },{ name: "建筑垃圾偷倒" }],

      timeshow: false,
      currentDate: "",
      minDate: new Date(2020, 0, 1),
      defaultDate: new Date(),

      showArea: false,
      address: "",
      map: null,
      lat:null,
      lng:null,

      gridvalue: "",
      gridshow: false,
      gridactions: [{ name: "0701" }, { name: "0702" }, { name: "0703" }],

      uploader: [],
      submitPic:[],

      endTimePop:false,
      currentDate_end:'',
      minDate: new Date(2021, 0, 1),
      searchMap:''
    };
  },
  mounted() {},
  methods: {
    onClickLeft() {
      this.$router.push({ path: "/eventDiscoveryMain" });
    },
    typeSelect(value) {
      this.typevalue = value.name;
      this.typeshow = false;
    },
    gridSelect(value) {
      this.gridvalue = value.name;
      this.gridshow = false;
    },
    // timeConfirm(date) {
    //   this.currentDate = `${date.getFullYear()}-${
    //     date.getMonth() + 1
    //   }-${date.getDate()}`;
    //   this.timeshow = false;
    // },
    addresshandle(val) {
      this.showArea = true;
      setTimeout(() => {
        this.map = new AMap.Map("gdmap", {
          zoom: 15,
          // center: [121.489658, 31.22478],
          center: [121.483793,31.219014],
        });
        let me = this;
        this.map.on("click", function (e) {
          me.regeoCode(e.lnglat);
        });
      });
    },
    onSearch(val) {
      Toast(val);
      this.placeSearch(val)
    },
    onCancel() {
      Toast('取消');
    },
    placeSearch(search){
      if(!search) return;
      let placeSearch = new AMap.PlaceSearch({
        city: '上海市', // 兴趣点城市，支持城市名、citycode、adcode
        citylimit: true, // 是否强制在设置的城市内搜索，默认false
        // type: '', // 兴趣点类别，用‘|’分隔，默认：'餐饮服务|商务住宅|生活服务'
        pageSize: 10, // 每页条数，默认10，范围1-50
        pageIndex: 1, // 页码
        extensions: 'all', // 默认base，返回基本地址信息；all：返回详细信息
        // map: map, // 地图实例，可选
        // panel: 'panel', // 结果列表的id容器，可选
        autoFitView: true, // 是否自动调整地图视野到marker点都处于可见范围
      })
      let that = this;
      placeSearch.search(search, function(status, result) {
        console.log(result)
        result.poiList.pois.forEach(e=>{
          that.Map_marker(e)
        })
      })
    },
    Map_marker(e){
      // 创建一个 Marker 实例：
      var marker = new AMap.Marker({
          position: new AMap.LngLat(e.location.lng, e.location.lat),   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
          title: e.address
      });

      // 将创建的点标记添加到已有的地图实例：
      this.map.add(marker);
      // let o = amapManager.getMap();
      // let marker = new AMap.Marker({
      //   position: [e.lng, e.lat]
      // });
      // marker.setMap(o);
    },
    regeoCode(lnglat) {
      // let marker = new AMap.Marker();
      let geocoder = new AMap.Geocoder({
        city: "021", //城市设为北京，默认：“全国”
        radius: 5000, //范围，默认：500
      });
      // this.map.add(marker);
      // marker.setPosition(lnglat);
      let me = this;
      geocoder.getAddress(lnglat, function (status, result) {
        if (status === "complete" && result.regeocode) {
          me.address = result.regeocode.formattedAddress;
          me.lat = result.regeocode.addressComponent.businessAreas[0].location.lat;
          me.lng = result.regeocode.addressComponent.businessAreas[0].location.lng;
          this.showArea = false;
        } else {
          log.error("根据经纬度查询地址失败");
        }
      });

    },
    // reporthandle(){
    //      this.$router.push({ path: "/eventDiscoveryMain/manualReportDone" });
    // },
    //图片上传前判断图片格式
    beforeRead(file) {
      if (
        file.type !== "image/jpeg" &&
        file.type !== "image/png" &&
        file.type !== "image/jpg" &&
        file.type !== "image/bmp" &&
        file.type !== "image/tif" &&
        file.type !== "image/gif" &&
        file.type !== "image/pcx" &&
        file.type !== "image/tga"
      ) {
        this.$toast.fail({
          message: "只可上传图片格式的文件"
        });
        return false;
      }
      return true;
    },
    //图片压缩
    afterRead(file) {
      this.ImageCompression(file)
    },
    //图片删除tab
    picDelete(file){
      const that = this
      for(let i=0;i<that.submitPic.length;i++){
        if (that.submitPic[i].picName === file.file.name) {
            that.submitPic.splice(i, 1);
            that.uploader.splice(i, 1);
          }
      }
    },
    //图片压缩
    ImageCompression(file){
      compressImage(file.content).then(result => {
        if (result.size > file.file.size) {
          //压缩后比原来更大，则将原图上传
          this.uploadFile(file.file, file.file.name, file);
        } else {
          //压缩后比原来小，上传压缩后的
          this.uploadFile(result, file.file.name, file);
        }
      });
    },
    //图片上传
    uploadFile(file, filename, files){
      var formData = new FormData(); //构造一个 FormData，把后台需要发送的参数添加
　　  formData.append('file', file,filename);
      uploadPic(formData).then((res) => {
        if (res.code === 200) {
          res.data['picName'] = filename;
          this.submitPic.push(res.data)
        }
      })
    },
    reporthandle(){
       //赋值给需要提交的属性
       let type = this.typevalue =='垃圾溢满'? 2 : (this.typevalue =='小包垃圾丢弃' ? 1:0)
       let params = {
         lat: this.lat,
         lng: this.lng,
         eventAddr: this.address,
         createTime: this.currentDate,
         eventType: type,
         imageUrls: this.submitPic,
         ownerGrid: this.gridvalue
       }
       disInsert(params).then((res)=>{
         if(res.code === 200){
           params['findkind'] = '人工上报';
           Toast.success(res.message)
           this.$router.push({name:'manualReportDone',params: {lists:params}})
         }else{
          Toast.fail(res.message)
        }
       })
    },
    //取消
    cancel(){
       this.$router.push({ path: "/" });
    },
    endTimeChange(e) {
      let endTimeArr = e.getValues();//["2019", "03", "22", "17", "28"]
      this.currentDate = `${endTimeArr[0]}-${endTimeArr[1]}-${endTimeArr[2]}  ${endTimeArr[3]}:${endTimeArr[4]}:00`
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.title {
  width: 100%;
  height: 35px;
  line-height: 35px;
  background: #daf4f1;
  color: #04bfac;
  font-weight: bold;
  text-align: center;
  margin-bottom: 5px;
  margin-top: 46px;
}
#gdmap {
  width: 100%;
  height: 400px;
}
.uploadbox {
  padding: 10px 20px;
  box-sizing: border-box;
}
.reportBtn {
  width: 90%;
  margin: 20px auto;
}
.cancel{
    width: 30px;
    height: 35px;
    line-height: 40px;
    margin: auto;
    text-align: center;
    color: #FF8F43;
    border-bottom: 2px #FF8F43 solid;
}
</style>
